﻿using Engine;
using Game.NetWork.Packages;
using Game.NetWork;
using Game.Server.Event;
using Game.Server.PlayerEvent;
using System;
using Game.IContentReader;
using System.Text;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using System.Web;

namespace Game.Server.Plugins
{
    public class NemesisZHPlugin : ServerPlugin, ICreatureHealthEventHandle
    {
        public override int Version => 10000;

        public override string Name => "天惩";

        public byte FirstLevel => 0;

        public static string ConfigFilePath;

        public SubsystemPickables subsystemPickables;

        public static Dictionary<string, int> NemesisCount = new Dictionary<string, int>();

        public override void Initialize()
        {
            CreatureHealthEventManager.AddObject(this);
        }

        public string GetPluginDataByWorldPath(string fileName)
        {
            string pluginDataPath = Storage.GetSystemPath("app:/PluginData");
            if (!Directory.Exists(pluginDataPath))
            {
                Directory.CreateDirectory(pluginDataPath);
            }
            string worldName = GameManager.Project.FindSubsystem<SubsystemGameInfo>().WorldSettings.Name;
            string dataByWorldPath = Storage.CombinePaths(pluginDataPath, worldName);
            if (!Directory.Exists(dataByWorldPath))
            {
                Directory.CreateDirectory(dataByWorldPath);
            }
            return Storage.CombinePaths(dataByWorldPath, fileName);
        }

        public override void Load()
        {
            ConfigFilePath = GetPluginDataByWorldPath("NemesisCount.json");
            try
            {
                NemesisCount.Clear();
                if (File.Exists(ConfigFilePath))
                {
                    using (StreamReader file = File.OpenText(ConfigFilePath))
                    {
                        string jsonText = file.ReadToEnd();
                        NemesisCount = JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonText);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"插件{Name}加载失败：{e.Message}");
            }
        }

        public override void Save()
        {
            try
            {
                string jsonText = JsonConvert.SerializeObject(NemesisCount);
                using (FileStream fileStream = File.Open(ConfigFilePath, FileMode.Create))
                {
                    using (StreamWriter fileWrite = new StreamWriter(fileStream))
                    {
                        fileWrite.Write(jsonText);
                        fileWrite.Flush();
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"插件{Name}保存失败：{e.Message}");
            }
        }

        public bool Heal(ComponentHealth componentHealth, float amount)
        {
            return true;
        }

        public bool Injure(ComponentHealth componentHealth, float amount, ComponentCreature attacker, string cause)
        {
            if(attacker != null && componentHealth != null)
            {
                ComponentPlayer player = attacker.Entity.FindComponent<ComponentPlayer>();
                ComponentPlayer player2 = componentHealth.Entity.FindComponent<ComponentPlayer>();
                if (player != null && player2 != null && componentHealth.Health > 0 && componentHealth.Health - amount <= 0)
                {
                    if (player.PlayerData.ServerManager) return true;
                    if(player2.PlayerData.ServerManager) 
                    {
                        componentHealth.Heal(amount * 2f);
                        ComponentHealth componentHealth2 = player.Entity.FindComponent<ComponentHealth>();
                        if (componentHealth2 != null)
                        {
                            componentHealth2.Injure(1f, null, true, "天惩！");
                        }
                        return true;
                    }
                    if (NemesisCount.ContainsKey(player.PlayerData.Client.CommunityAccountId))
                    {
                        NemesisCount[player.PlayerData.Client.CommunityAccountId] += 1;
                    }
                    else
                    {
                        NemesisCount[player.PlayerData.Client.CommunityAccountId] = 1;
                    }
                    if(NemesisCount[player.PlayerData.Client.CommunityAccountId] == 2)
                    {
                        DisplaySmallMessageNet(player, "你已经嘎了2人，请停止你的行为！");
                    }
                    if(NemesisCount[player.PlayerData.Client.CommunityAccountId] > 2)
                    {
                        ComponentHealth componentHealth2 = player.Entity.FindComponent<ComponentHealth>();
                        if(componentHealth2 != null)
                        {
                            componentHealth2.Injure(1f, null, true, "天惩！");
                        }
                    }
                }
            }
            return true;
        }

        public void DisplaySmallMessageNet(ComponentPlayer componentPlayer, string text)
        {
            var messagePackget = new MessagePackage(null, text, 0, null);
            messagePackget.To = componentPlayer.PlayerData.Client;
            CommonLib.Net.QueuePackage(messagePackget);
        }
    }
}